package org.mili.ticketeer.report;

import org.apache.commons.io.FileUtils;
import org.mili.core.templating.TemplateStore;
import org.mili.ticketeer.dto.Group;
import org.mili.ticketeer.dto.Ticket;
import org.mili.application.service.ServiceException;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class RequestTicketGenerator extends AbstractGenerator {

    public RequestTicketGenerator(ReportEngine reportEngine, TemplateStore templateStore) {
        super(reportEngine, templateStore);
    }

    public void generate() throws IOException, ServiceException {
        System.out.println("generate");
        StringBuilder s1 = new StringBuilder();
        String temp1 = templateStore.get("tickets_request_Group");
        String temp2 = templateStore.get("tickets_request_Group_Item");
        for(Map.Entry<Group, List<Ticket>> entry : reportEngine.getTicketsByGroups().entrySet()) {
            StringBuilder s2 = new StringBuilder();
            boolean found = false;
            for(Ticket ticket : reportEngine.getRequestTickets(entry.getValue())) {
                s2.append(reportEngine.replaceWithTicket(temp2, ticket));
                found = true;
            }
            if (found) {
                s1.append(temp1
                        .replace("${group_name}", reportEngine.getHtml(entry.getKey().getName()))
                        .replace("${Group_Item}", s2)
                        );
            }
        }
        SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
        FileUtils.writeStringToFile(new File("./tmp/out/punkte_rueckfragen.html"),
                templateStore.get("tickets_request_Main")
                        .replace("${Group}", s1)
                        .replace("${date}", format.format(new Date()))
                        .replace("${title}", "Punkte zur R&uuml;ckfrage")
        );
    }

}
